//
//  History.m
//  CarTown
//
//  Created by xionghao on 15/9/25.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "History.h"
#import "AppDelegate.h"

@implementation History

@dynamic name;
@dynamic time;
@dynamic type;
+(void)addHistory:(NSString *)string WithType:(NSString *)type{
    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    [History deletmoreitem:string withType:type];
    History *addh=[NSEntityDescription insertNewObjectForEntityForName:@"History" inManagedObjectContext:delegate.managedObjectContext];
    addh.name=string;
    addh.time=[NSDate date];
    addh.type=type;
    [delegate saveContext];
}
-(void)deleteHistory {
    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    [delegate.managedObjectContext deleteObject:self];
    [delegate saveContext];
}
+(void)deletmoreitem:(NSString *)text withType:(NSString *)type{
    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"History"];
    
    NSPredicate *pre=[NSPredicate predicateWithFormat:@"name=%@ and type=%@",text,type];
    request.predicate=pre;
    NSArray *sets= [delegate.managedObjectContext executeFetchRequest:request error:nil];
    if (sets.count>0) {
        [delegate.managedObjectContext deleteObject:sets[0]];
    }
    request.predicate=nil;
     NSArray *sets2= [delegate.managedObjectContext executeFetchRequest:request error:nil];
    if (sets2.count==10) {
          [delegate.managedObjectContext deleteObject:sets2[0]];
    }
    [delegate saveContext];
    
}

+(NSArray *)gethistroysbyType:(NSString *)type{
    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"History"];
    NSPredicate *pre=[NSPredicate predicateWithFormat:@"type=%@",type];
    request.predicate=pre;
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors=@[sort];
    NSArray *sets= [delegate.managedObjectContext executeFetchRequest:request error:nil];
    return sets;
}


@end
